/**
 * @desc 上传组件
 * @props { bool } disabled 是否显示上传控件
 * @props { number | string } 上传数量
 */
import React from 'react'
import PropTypes from 'prop-types'
import { Upload, Modal } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { withRouter } from 'react-router-dom'
import { getBase } from '@/utils/getBase'

class TheUpload extends React.Component {
    state = {
        previewVisible: false,
        previewImage: '',
        previewTitle: '',
        fileList: [],
    };

    componentDidMount() {
        if (this.props.fileList) {
            this.setState({ fileList: this.props.fileList })
        }
    }

    componentDidUpdate(prevProps, prevState, snapshot) {
        const preFileList = JSON.stringify(prevProps.fileList)
        const fileList = JSON.stringify(this.props.fileList)
        if (preFileList !== fileList) {
            this.setState({
                fileList: this.props.fileList
            })
        }
    }

    handleCancel = () => this.setState({ previewVisible: false });

    handlePreview = async file => {
        if (!file.url && !file.preview) {
            file.preview = await getBase(file.originFileObj);
        }
        this.setState({
            previewImage: file.url || file.preview,
            previewVisible: true,
            previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
        });
    };

    handleChange = ({ file, fileList }) => {
        if (file.size / 1024 / 1024 >= 5) {
            return
        }
        if (file && fileList && fileList.length) {
            fileList = fileList.map(v => {
                if (v.status === 'done') {
                    if (v.response && v.response.code === 0 && v.response.data) {
                        return v
                    } else {
                        return {
                            ...v,
                            status: 'error'
                        }
                    }
                } else {
                    return v
                }
            })
        }
        //过滤数据大于10M的数据
        fileList = fileList.filter(v => (v.size / 1024 / 1024 < 5 || v.status === 'done'))
        this.props.getFileResult(fileList, this.props.pid, this.props.index)
        this.setState({ fileList })
    };

    render() {
        const { previewVisible, previewImage, fileList, previewTitle } = this.state;
        const { len, disabled, label } = this.props;
        const uploadButton = (
            <div>
                <PlusOutlined />
                <div style={{ marginTop: 8 }}>{label}</div>
            </div>
        );
        const checkFileSize = (file) => {
            if (file.size / 1024 / 1024 < 5) {
                return true
            } else {
                React.$message({
                    type: 'info',
                    content: '文件最大不能超过5M'
                })
                return false
            }
        };
        return (
            <>
                <Upload
                    action={"/management/oss/image/upload"}
                    listType="picture-card"
                    fileList={fileList}
                    accept={'image/*'}
                    headers={{ RSnetToken: sessionStorage.getItem('RSnetToken') }}
                    beforeUpload={checkFileSize}
                    onPreview={this.handlePreview}
                    onChange={this.handleChange}>
                    {(fileList.length >= len || disabled) ? null : uploadButton}
                </Upload>
                <Modal
                    visible={previewVisible}
                    title={previewTitle}
                    footer={null}
                    onCancel={this.handleCancel}>
                    <img alt="example" style={{ width: '100%' }} src={previewImage} />
                </Modal>
            </>
        );
    }
}

TheUpload.propTypes = {
    disabled: PropTypes.bool,//上传按钮是否显示
    len: PropTypes.number,//最大上传数量
    label: PropTypes.string,
    getFileResult: PropTypes.func,
    pid: PropTypes.number,
    index: PropTypes.number
}
TheUpload.defaultProps = {
    disabled: false,
    len: 5,
    label: 'Upload'
}
export default withRouter(TheUpload)
